package cn.sdormitory.homeschool.service.impl;

import cn.sdormitory.basedata.dao.BStudentDao;
import cn.sdormitory.basedata.entity.BStudent;
import cn.sdormitory.common.MD5;
import cn.sdormitory.common.TokenService;
import cn.sdormitory.common.exception.ApiException;
import cn.sdormitory.common.sms.TxSmsTemplate;
import cn.sdormitory.common.utils.RedisUtils;
import cn.sdormitory.exam.dao.ExamResultInfoDao;
import cn.sdormitory.exam.vo.ExamResultInfoAppVo;
import cn.sdormitory.exam.vo.ExamResultInfoVO;
import cn.sdormitory.homeschool.service.HomeSchoolService;
import cn.sdormitory.smartclass.dao.ClassAttenceDao;
import cn.sdormitory.smartclass.dao.ClassDvDao;
import cn.sdormitory.smartclass.entity.ClassAttence;
import cn.sdormitory.smartclass.entity.ClassDv;
import cn.sdormitory.smartclass.service.ClassDvService;
import cn.sdormitory.smartclass.vo.ClassAttenceVo;
import cn.sdormitory.smartclass.vo.ClassDvAppVo;
import cn.sdormitory.smartclass.vo.ClassDvVo;
import cn.sdormitory.smartdor.dao.SdAttenceDao;
import cn.sdormitory.smartdor.dao.StudentTrajectoryDao;
import cn.sdormitory.smartdor.entity.SdAttence;
import cn.sdormitory.smartdor.entity.StudentTrajectory;
import cn.sdormitory.smartdor.vo.SdAttenceAppVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class HomeSchoolServiceImpl implements HomeSchoolService {

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private TxSmsTemplate txSmsTemplate;

    @Autowired
    private BStudentDao bStudentDao;

    @Autowired
    ExamResultInfoDao examResultInfoDao;

    @Autowired
    ClassDvDao classDvDao;

    @Autowired
    ClassAttenceDao classAttenceDao;

    @Autowired
    SdAttenceDao sdAttenceDao;

    @Autowired
    StudentTrajectoryDao studentTrajectoryDao;

    @Override
    public String noLogin(String token) {
        return redisUtils.get(token);
    }

    @Override
    public String parentLogin(Map<String, String> loginParam) {
        String phone = loginParam.get("phone");
        String code = loginParam.get("code");
        if(StringUtils.isEmpty(phone) || StringUtils.isEmpty(code)){
            throw new ApiException("请输入手机或验证码");
        }
        String cacheCode = redisUtils.get("login:validCode:" + phone);
        if(!code.equals(cacheCode)){
            throw new ApiException("验证码不正确");
        }
        redisUtils.delete("login:validCode:" + phone);

        try{
            StringBuilder sb = new StringBuilder();
            sb.append("homeSchool:");
            sb.append("MOBILE-");
            sb.append(MD5.getMd5(phone,32) + "-");//加密手机号
            sb.append(code + "-");
            sb.append(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()));
            String token = sb.toString();
            //将手机号保存至缓存中避免，频繁登录
            redisUtils.set(token,phone,43200L);
            return token;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void sendValidCode(String phone) throws ApiException {
        if(StringUtils.isEmpty(phone)){
            throw new ApiException("请输入手机号码");
        }

        QueryWrapper<BStudent> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_phone",phone);
        List<BStudent> bStudents = bStudentDao.selectList(wrapper);
        if(bStudents == null || bStudents.size() <= 0) {
            throw new ApiException("非学生家长手机号，无法登录");
        }

        String repeatFlag = redisUtils.get("repeat:validCode:" + phone);
        if(!StringUtils.isEmpty(repeatFlag)){
            throw new ApiException("请勿重复发送");
        }

        //生成随机4位数的验证码
        String code = String.valueOf(Math.round((Math.random()+1) * 1000));
        String[] params = {code};

        String resultStr = txSmsTemplate.sendMesModel(phone,params,0);
        if("OK".equals(resultStr)){
            //发送成功，将验证码保存到缓存中，设置5分钟过期，验证成功后删除
            redisUtils.set("login:validCode:" + phone,code,300L);

            redisUtils.set("repeat:validCode:" + phone,phone,60);
        }else {
            throw new ApiException(resultStr);

        }
    }

    @Override
    public List<ExamResultInfoAppVo> getParenChildExamResult(String phone) {
        QueryWrapper<BStudent> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_phone",phone);
        List<BStudent> bStudents = bStudentDao.selectList(wrapper);
        List<ExamResultInfoAppVo> result = new ArrayList<>();
        if(bStudents != null && bStudents.size() > 0){
            for(BStudent bStudent : bStudents){
                result.addAll(examResultInfoDao.findResultByStudentNo(bStudent.getStudentNo()));
            }
        }
        return result;
    }

    @Override
    public List<ClassDvAppVo> getParenChildDv(String phone) {
        QueryWrapper<BStudent> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_phone",phone);
        List<BStudent> bStudents = bStudentDao.selectList(wrapper);
        List<ClassDvAppVo> result = new ArrayList<>();
        if(bStudents != null && bStudents.size() > 0){
            for(BStudent bStudent : bStudents){
                result.addAll(classDvDao.findClassDvByStuNo(bStudent.getStudentNo()));
            }
        }
        return result;
    }

    @Override
    public List<ClassAttenceVo> getParenChildClassAttendance(String phone) {
        QueryWrapper<BStudent> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_phone",phone);
        List<BStudent> bStudents = bStudentDao.selectList(wrapper);
        List<ClassAttenceVo> result = new ArrayList<>();
        if(bStudents != null && bStudents.size() > 0){
            for(BStudent bStudent : bStudents){
                result.addAll(classAttenceDao.findClassAttendanceByStuNo(bStudent.getStudentNo()));
            }
        }
        return result;
    }

    @Override
    public List<SdAttenceAppVo> getParenChildDorAttendance(String phone) {
        QueryWrapper<BStudent> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_phone",phone);
        List<BStudent> bStudents = bStudentDao.selectList(wrapper);
        List<SdAttenceAppVo> result = new ArrayList<>();
        if(bStudents != null && bStudents.size() > 0){
            for(BStudent bStudent : bStudents){
                result.addAll(sdAttenceDao.findSdAttenceByStuNo(bStudent.getStudentNo()));
            }
        }
        return result;
    }

    @Override
    public List<StudentTrajectory> getParenChildTrajectory(String phone) {
        QueryWrapper<BStudent> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_phone",phone);
        List<BStudent> bStudents = bStudentDao.selectList(wrapper);
        List<StudentTrajectory> result = new ArrayList<>();
        if(bStudents != null && bStudents.size() > 0){
            for(BStudent bStudent : bStudents){
                result.addAll(studentTrajectoryDao.getInfoByStudentId(bStudent.getId()));
            }
        }
        return result;
    }
}
